<template>
  <div class="app-container">
    <!-- 筛选区域 -->
    <div class="filter-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px">
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="时间范围" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <div class="stat-card">
        <div class="card-title">今日用水量</div>
        <div class="value-number">{{ statistics.todayUsage }} 吨</div>
        <div>较昨日 <span :class="statistics.dayCompare >= 0 ? 'text-success' : 'text-danger'">
                    {{ statistics.dayCompare >= 0 ? '+' + statistics.dayCompare : statistics.dayCompare }}%
                </span></div>
      </div>
      <div class="stat-card">
        <div class="card-title">本月用水量</div>
        <div class="value-number">{{ statistics.monthUsage }} 吨</div>
        <div>较上月 <span :class="statistics.monthCompare >= 0 ? 'text-success' : 'text-danger'">
                    {{ statistics.monthCompare >= 0 ? '+' + statistics.monthCompare : statistics.monthCompare }}%
                </span></div>
      </div>
      <div class="stat-card">
        <div class="card-title">平均日用水量</div>
        <div class="value-number">{{ statistics.avgDailyUsage }} 吨</div>
        <div>近30天平均值</div>
      </div>
      <div class="stat-card">
        <div class="card-title">峰值用水量</div>
        <div class="value-number">{{ statistics.peakUsage }} 吨</div>
        <div>发生日期：{{ statistics.peakDate }}</div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="chart-container">
      <div class="chart-title">用户用水量趋势图</div>
      <div id="waterChart" style="width: 100%; height: 400px;"></div>
    </div>

    <!-- 用水量分布 -->
    <div class="chart-container">
      <div class="chart-title">日用水量分布</div>
      <div id="distributionChart" style="width: 100%; height: 400px;"></div>
    </div>
  </div>
</template>

<script>
import { listWaterData} from "@/api/meterread/waterAnalysis";
import * as echarts from 'echarts';
export default {
  name: "WaterAnalysis",
  data() {
    // 设置默认日期范围为最近30天
    const end = new Date();
    const start = new Date();
    start.setDate(start.getDate() - 30);
    return {
      // 查询参数
      queryParams: {
        userName: '张三',
        dateRange: [this.formatDate(start), this.formatDate(end)]
      },
      // 统计数据
      statistics: {
        todayUsage: 12.5,
        dayCompare: 8.7,
        monthUsage: 342.8,
        monthCompare: -3.2,
        avgDailyUsage: 11.4,
        peakUsage: 18.6,
        peakDate: '2023-06-15'
      },
      // 图表实例
      waterChart: null,
      distributionChart: null
    };
  },
  mounted() {
    this.initChart();
    this.loadData();

    // 响应窗口大小变化，调整图表尺寸
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
  },
  methods: {
    // 初始化图表
    initChart() {
      this.waterChart  = echarts.init(document.getElementById('waterChart'));
      this.distributionChart = echarts.init(document.getElementById('distributionChart'));
      // 用水量趋势图配置
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>用水量: {c} 吨'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: []
        },
        yAxis: {
          type: 'value',
          name: '用水量(吨)',
          min: 0
        },
        series: [{
          name: '用水量',
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: {
            color: '#409EFF'
          },
          lineStyle: {
            width: 3
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(64, 158, 255, 0.6)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ])
          },
          data: []
        }]
      };

      // 用水量分布图配置
      const distributionOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['0-5吨', '5-10吨', '10-15吨', '15-20吨', '20吨以上']
        },
        yAxis: {
          type: 'value',
          name: '天数'
        },
        series: [{
          name: '天数',
          type: 'bar',
          barWidth: '60%',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          },
          data: [5, 12, 8, 4, 1]
        }]
      };

      this.waterChart.setOption(option);
      this.distributionChart.setOption(distributionOption);
    },

    // 加载数据
    loadData() {
      // 模拟API调用
      // this.$axios.get('/water/usage/data', { params: this.queryParams }).then(response => {
      //     const data = response.data;
      //     this.statistics = data.statistics;
      //     this.updateChart(data.chartData);
      // });

      // 模拟数据
      /*const mockData = {
        dates: ['6-01', '6-02', '6-03', '6-04', '6-05', '6-06', '6-07', '6-08', '6-09', '6-10',
          '6-11', '6-12', '6-13', '6-14', '6-15', '6-16', '6-17', '6-18', '6-19', '6-20',
          '6-21', '6-22', '6-23', '6-24', '6-25', '6-26', '6-27', '6-28', '6-29', '6-30'],
        values: [10.2, 11.5, 9.8, 12.3, 13.6, 8.7, 10.9, 14.2, 15.7, 12.8,
          11.3, 13.5, 16.2, 17.4, 18.6, 15.3, 12.7, 11.8, 14.5, 13.2,
          10.8, 12.4, 14.7, 16.3, 13.8, 11.6, 10.5, 12.9, 14.3, 13.5]
      };
      this.updateChart(mockData);*/
      // 生成模拟数据
      const mockData = this.generateMockData();

      // 更新统计信息
      this.updateStatistics(mockData);

      // 更新图表
      this.waterChart.setOption({
        xAxis: {
          data: mockData.dates
        },
        series: [{
          data: mockData.values
        }]
      });

      // 更新分布图
      this.updateDistributionChart(mockData.values);
    },
    // 更新分布图
    updateDistributionChart(values) {
      const ranges = [0, 0, 0, 0, 0]; // 0-5, 5-10, 10-15, 15-20, 20+

      values.forEach(value => {
        if (value < 5) ranges[0]++;
        else if (value < 10) ranges[1]++;
        else if (value < 15) ranges[2]++;
        else if (value < 20) ranges[3]++;
        else ranges[4]++;
      });

      this.distributionChart.setOption({
        series: [{
          data: ranges
        }]
      });
    },

    // 更新图表数据
    updateChart(chartData) {
      this.chart.setOption({
        xAxis: {
          data: chartData.dates
        },
        series: [{
          data: chartData.values
        }]
      });
    },

    // 生成模拟数据
    generateMockData() {
      const userType = this.queryParams.userName;
      let baseUsage, variance, weekendMultiplier;

      // 根据用户类型设置不同的用水模式
      switch(userType) {
        case '李四': // 商业用户
          baseUsage = 15;
          variance = 4;
          weekendMultiplier = 0.7; // 周末用水减少
          break;
        case '王五': // 工业用户
          baseUsage = 25;
          variance = 8;
          weekendMultiplier = 0.5; // 周末用水大幅减少
          break;
        case '赵六': // 农业用户
          baseUsage = 30;
          variance = 15;
          weekendMultiplier = 1.2; // 周末用水增加
          break;
        default: // 居民用户（张三）
          baseUsage = 10;
          variance = 3;
          weekendMultiplier = 1.3; // 周末用水增加
      }

      const dates = [];
      const values = [];
      const startDate = new Date(this.queryParams.dateRange[0]);
      const endDate = new Date(this.queryParams.dateRange[1]);
      const days = Math.floor((endDate - startDate) / (1000 * 60 * 60 * 24)) + 1;

      // 生成日期和用水量数据
      for (let i = 0; i < days; i++) {
        const currentDate = new Date(startDate);
        currentDate.setDate(startDate.getDate() + i);

        const dateStr = this.formatDate(currentDate);
        dates.push(dateStr);

        // 模拟周末效应
        const isWeekend = currentDate.getDay() === 0 || currentDate.getDay() === 6;
        let dailyUsage = baseUsage + (Math.random() - 0.5) * variance;

        if (isWeekend) {
          dailyUsage *= weekendMultiplier;
        }

        // 添加一些随机峰值
        if (Math.random() > 0.9) {
          dailyUsage *= 1.5;
        }

        values.push(parseFloat(dailyUsage.toFixed(1)));
      }

      return { dates, values };
    },
    // 更新统计信息
    updateStatistics(data) {
      const values = data.values;
      const total = values.reduce((sum, val) => sum + val, 0);
      const avg = total / values.length;
      const peak = Math.max(...values);
      const peakIndex = values.indexOf(peak);

      this.statistics = {
        todayUsage: values[values.length - 1],
        dayCompare: parseFloat(((values[values.length - 1] - values[values.length - 2]) / values[values.length - 2] * 100).toFixed(1)),
        monthUsage: parseFloat(total.toFixed(1)),
        monthCompare: parseFloat((Math.random() * 10 - 5).toFixed(1)), // 随机变化-5%到5%
        avgDailyUsage: parseFloat(avg.toFixed(1)),
        peakUsage: peak,
        peakDate: data.dates[peakIndex]
      };
    },

    // 调整图表尺寸
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    },

    // 处理查询
    handleQuery() {
      this.loadData();
    },
    // 格式化日期为YYYY-MM-DD
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 重置查询
    resetQuery() {
      this.queryParams = {
        userName: '张三',
        dateRange: this.queryParams.dateRange
      };
      this.$refs.queryForm.resetFields();
      this.loadData();
    }
  }
};
</script>
<style scoped>
.filter-card {
  margin-bottom: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}
.statistics-cards {
  display: flex;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}
.stat-card {
  flex: 1;
  min-width: 230px;
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}
.chart-container {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 500px;
  margin-bottom: 20px;
}
.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}
.el-form-item {
  margin-bottom: 15px;
}
.value-number {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin: 10px 0;
}
.card-title {
  color: #666;
  font-size: 14px;
}
.text-success {
  color: #67c23a;
}
.text-danger {
  color: #f56c6c;
}
.card-icon {
  font-size: 24px;
  margin-bottom: 10px;
  color: #409EFF;
}
.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}
.filter-item {
  flex: 1;
  min-width: 280px;
}
@media (max-width: 768px) {
  .stat-card {
    min-width: 100%;
  }
  .filter-item {
    min-width: 100%;
  }
}
</style>
